package com.fresh.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fresh.common.ResponseResult;
import com.fresh.entity.FreshGoods;
import com.fresh.entity.Orders;
import com.fresh.system.service.OrdersService;
import com.fresh.system.until.GoodsClient;
import com.fresh.system.until.OrderCodeFactory;
import com.fresh.system.vo.PayForO;
import com.fresh.system.vo.PayForOs;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Wx
 * @Date:2023/08/10/14:27
 * @Description:
 */
@RestController
@RequestMapping("orders")
public class OrdersController {
    @Resource
    private OrdersService ordersService;
    @Resource
    private GoodsClient goodsClient;
    @RequestMapping("selectById")
    public ResponseResult selectById(HttpServletRequest httpServletRequest) {
        String userId ="1";
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("clientId",userId);
        List<Orders> list = ordersService.list(queryWrapper);
        return ResponseResult.success(list);
    }
    @RequestMapping("delete")
    public ResponseResult delete(@RequestBody Orders orders) {
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("orders",orders);
        ordersService.remove(queryWrapper);
        return ResponseResult.success();
    }
    @GetMapping("/add")
    public ResponseResult<Orders> add(@RequestParam("goodsId") Integer goodsId, @RequestParam("num")Integer num, @RequestParam("address")String address, HttpServletRequest httpServletRequest) throws JsonProcessingException {
//        String userId = httpServletRequest.getHeader("userId");
        String userId ="1";
        Orders orders=new Orders();
        orders.setClientId(Integer.valueOf(userId));
        orders.setAddress(address);
        orders.setStatus("y");
        FreshGoods goods = JSONObject.parseObject(new ObjectMapper().writeValueAsString(goodsClient.selectById(goodsId).getData()),FreshGoods.class);
        orders.setTotalMoney(goods.getPrice().multiply(BigDecimal.valueOf(num)));
        orders.setOrderTime(LocalDateTime.now());
        orders.setNo(OrderCodeFactory.getOrderCode(Long.valueOf(userId)));
        ordersService.add(orders,goodsId,num);
        return ResponseResult.success(orders);
    }
    @PostMapping("/pay")
    public ResponseResult<List<Orders>> pay(@RequestBody PayForOs payForOs, HttpServletRequest httpServletRequest) throws JsonProcessingException {
        String userId = "1";
        Orders orders = new Orders();
        List<Orders> orderList = new ArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建线程池
        List<Future<Orders>> futures = new ArrayList<>();
        for (PayForO pay : payForOs.getPay()) {
            Future<Orders> future = executorService.submit(() -> {
                Integer goodsId = pay.getGoodsId();
                Integer num = pay.getNum();
                String address = pay.getAddress();
                orders.setClientId(Integer.valueOf(userId));
                orders.setAddress(address);
                orders.setStatus("y");
                FreshGoods goods = JSONObject.parseObject(new ObjectMapper().writeValueAsString(goodsClient.selectById(goodsId).getData()), FreshGoods.class);
                orders.setTotalMoney(goods.getPrice().multiply(BigDecimal.valueOf(num)));
                orders.setOrderTime(LocalDateTime.now());
                orders.setNo(OrderCodeFactory.getOrderCode(Long.valueOf(userId)));

                ordersService.add(orders, goodsId, num);
                return orders;
            });
            futures.add(future);
        }

        for (Future<Orders> future : futures) {
            try {
                Orders completedOrder = future.get();
                orderList.add(completedOrder);
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常
            }
        }

        executorService.shutdown(); // 关闭线程池

        return ResponseResult.success(orderList);
    }

    @PostMapping("update")
    public ResponseResult<Void> update(@RequestBody Orders orders){
        QueryWrapper<Orders>queryWrapper=new QueryWrapper<>(orders);
        ordersService.update(queryWrapper);
        return ResponseResult.success();
    }
}
